<template>
  <!-- 模板部分不变，保持你原有的HTML结构 -->
  <el-submenu 
    v-if="hasChildren" 
    :index="item.id.toString()"
    :popper-append-to-body="false"
    :style="{ '--level': level }"
  >
    <template #title>
      <input 
        type="checkbox" 
        :checked="isChecked"
        :indeterminate="isIndeterminate"
        @change="handleCheck"
        style="margin-right: 8px; position: relative; z-index: 100;"
      >
      <i :class="item.icon || 'el-icon-menu'"></i>
      <span>{{ item.name }}</span>
    </template>
    
    <template v-for="child in item.children">
      <permission-sidebar-item
        :key="child.id"
        :item="child"
        :level="level + 1"
        :checked-keys="checkedKeys"
        :parent-id="item.id" 
        @update:checkedKeys="$emit('update:checkedKeys', $event)"
      />
    </template>
  </el-submenu>

  <el-menu-item 
    v-else 
    :index="item.id.toString()"
  >
    <input 
      type="checkbox" 
      :checked="isChecked"
      @change="handleCheck"
      style="margin-right: 8px; position: relative; z-index: 100;"
    >
    <i :class="item.icon || 'el-icon-document'"></i>
    <span>{{ item.name }}</span>
  </el-menu-item>
</template>

<script>
export default {
  name: "PermissionSidebarItem",
  props: {
    item: { type: Object, required: true },
    level: { type: Number, default: 1 },
    checkedKeys: { type: Array, default: () => [] },
    parentId: { type: [Number, String], default: null } // 新增：接收父菜单ID
  },
  computed: {
    hasChildren() {
      return Array.isArray(this.item.children) && this.item.children.length > 0;
    },
    // 修正：父菜单是否选中（自身ID在列表中则选中，不再依赖子菜单）
    isChecked() {
      const currentId = Number(this.item.id);
      return this.checkedKeys.includes(currentId);
    },
    // 父菜单半选状态（部分子菜单选中）
    isIndeterminate() {
      if (!this.hasChildren) return false;
      const childIds = this.getAllChildIds(this.item); // 所有子菜单ID
      const checkedChildCount = childIds.filter(id => this.checkedKeys.includes(id)).length;
      return checkedChildCount > 0 && checkedChildCount < childIds.length;
    }
  },
  methods: {
    handleCheck(e) {
      const checked = e.target.checked;
      const currentId = Number(this.item.id);
      let newCheckedKeys = [...this.checkedKeys];

      if (this.hasChildren) {
        // 父菜单勾选：1. 添加/移除自身ID 2. 联动所有子菜单
        if (checked) {
          // 勾选：加父ID + 所有子ID
          if (!newCheckedKeys.includes(currentId)) newCheckedKeys.push(currentId);
          this.addAllChildIds(newCheckedKeys, this.item);
        } else {
          // 取消：删父ID + 所有子ID
          newCheckedKeys = newCheckedKeys.filter(id => id !== currentId);
          this.removeAllChildIds(newCheckedKeys, this.item);
        }
      } else {
        // 子菜单勾选：1. 添加/移除自身ID 2. 自动添加父ID
        if (checked) {
          // 勾选：加自身ID + 父ID（若有父ID且未添加）
          if (!newCheckedKeys.includes(currentId)) newCheckedKeys.push(currentId);
          if (this.parentId) {
            const parentIdNum = Number(this.parentId);
            if (!newCheckedKeys.includes(parentIdNum)) newCheckedKeys.push(parentIdNum);
          }
        } else {
          // 取消：删自身ID + 检查父菜单是否需取消
          newCheckedKeys = newCheckedKeys.filter(id => id !== currentId);
          this.checkAndRemoveParent(newCheckedKeys);
        }
      }

      // 去重并触发更新
      newCheckedKeys = [...new Set(newCheckedKeys)];
      this.$emit("update:checkedKeys", newCheckedKeys);
    },
    // 递归获取所有子菜单ID
    getAllChildIds(menu) {
      let childIds = [];
      if (menu.children && menu.children.length) {
        menu.children.forEach(child => {
          childIds.push(Number(child.id));
          childIds = [...childIds, ...this.getAllChildIds(child)];
        });
      }
      return childIds;
    },
    // 递归添加所有子菜单ID
    addAllChildIds(keysArr, menu) {
      if (menu.children && menu.children.length) {
        menu.children.forEach(child => {
          const childId = Number(child.id);
          if (!keysArr.includes(childId)) keysArr.push(childId);
          this.addAllChildIds(keysArr, child);
        });
      }
    },
    // 递归移除所有子菜单ID
    removeAllChildIds(keysArr, menu) {
      if (menu.children && menu.children.length) {
        menu.children.forEach(child => {
          const childId = Number(child.id);
          const index = keysArr.indexOf(childId);
          if (index !== -1) keysArr.splice(index, 1);
          this.removeAllChildIds(keysArr, child);
        });
      }
    },
    // 取消子菜单后，检查父菜单是否需取消（所有子都取消则删父ID）
    checkAndRemoveParent(keysArr) {
      if (!this.parentId) return;
      const parentIdNum = Number(this.parentId);
      // 找到父菜单
      const parentMenu = this.findParentMenu(this.parentId);
      if (!parentMenu) return;
      // 获取父菜单的所有子ID
      const allChildIds = this.getAllChildIds(parentMenu);
      // 检查是否还有子ID在选中列表中
      const hasCheckedChild = allChildIds.some(id => keysArr.includes(id));
      // 没有子选中 → 移除父ID
      if (!hasCheckedChild && keysArr.includes(parentIdNum)) {
        keysArr.splice(keysArr.indexOf(parentIdNum), 1);
      }
    },
    // 从当前菜单向上查找父菜单（基于父ID）
    findParentMenu(targetParentId) {
      const findMenu = (menus) => {
        for (const menu of menus) {
          if (Number(menu.id) === Number(targetParentId)) return menu;
          if (menu.children && menu.children.length) {
            const found = findMenu(menu.children);
            if (found) return found;
          }
        }
        return null;
      };
      // 从根菜单开始找（需先给根菜单加children，若没有则手动包裹）
      const rootMenus = Array.isArray(this.$parent.permissionMenuData) 
        ? this.$parent.permissionMenuData 
        : [this.$parent.permissionMenuData];
      return findMenu(rootMenus);
    }
  }
};
</script>